package org.example.servletpractice.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

@WebServlet(name = "CookieServlet",value = "/cookieServlet")
public class CookieServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie name = new Cookie("username", URLEncoder.encode(req.getParameter("username"),"UTF-8"));
        Cookie age = new Cookie("age", req.getParameter("age"));

        //设置保存时间
        name.setMaxAge(60*60*24);
        age.setMaxAge(60*60*24);

        resp.addCookie(name);
        resp.addCookie(age);

        //设置响应内容
        resp.setContentType("text/html;charset=UTF-8");

        PrintWriter writer = resp.getWriter();
        writer.println("<h1>姓名: "+req.getParameter("username")+"</h1>");
        writer.println("<h2>年龄: "+req.getParameter("age")+"</h2>");

    }

}
